 <!-- 管理员页面 -->
<template>
  <div class="box_container">
    <!-- 输入框 -->
    <div class="box_input">
      <el-input v-model="list.username" placeholder="请输入管理员名称" @input="inputchang"></el-input>
      <el-button icon="el-icon-search" type="primary" @click="onSeek">查找</el-button>
      <el-button icon="el-icon-plus" type="primary" @click="addAdmin">添加</el-button>
    </div>
    <!-- 管理员列表 -->
    <div class="box_table">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="管理员ID">
        </el-table-column>
        <el-table-column prop="username" label="管理员名称">
        </el-table-column>
        <el-table-column prop="realname" label="真实姓名">
        </el-table-column>
        <el-table-column prop="phone" label="电话">
        </el-table-column>
        <el-table-column label="管理员角色">
          <template slot-scope="scope">
            <template v-for="item in getRoleNames(scope.row.roleIds) ">
              <el-tag :key="item.value">{{item.label}}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加--修改弹框 -->
    <el-dialog :title="title" :visible.sync="dialogTableVisible">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" :disabled='title=="添加"?false:true'></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="showPrise">
          <el-input v-model="ruleForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="ruleForm.realname"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择">
            <el-option v-for="item in adminrRole" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end;">
          <el-button type="primary" @click="submitForm('ruleForm')">{{title=="添加"?"添加":"修改"}}</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分页 -->
    <div class="box_paging">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="list.page" :page-sizes="[10, 30, 50, 100]" :page-size="list.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 回到顶部-->
    <el-backtop target=".el-main" :bottom="20" :right="200" ref="roll"></el-backtop>
  </div>
</template>
<script>
import Apiadmin from "../../api/admin"
export default {
  data() {
    return {
      tableData: [],
      total: 0, //数据总条数
      list: {
        limit: 10, //每页显示的数量
        page: 1,  //当前显示的页码
        username: '', //管理员名称搜索
      },
      dialogTableVisible: false, //添加弹框显示或隐藏
      ruleForm: {
        username: '', //用户名
        password: '',//密码
        phone: '',//手机号
        realname: '',//真实姓名
        roleIds: [], //角色
      },
      // 表单验证
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在3到15个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^0?(13|14|15|17|18|19)[0-9]{9}$/, message: '手机号格式错误', trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      },
      adminrRole: [],  //角色枚举数据
      adminDTO: {},   //管理员添加参数
      title: '', //弹出框添加或修改
      showPrise: false //密码框隐藏
    }
  },
  created() {
    this.adminList()
  },

  methods: {
    //查找管理员输入框 
    inputchang(e) {
      console.log(e)
      this.username = e
    },
    //查找管理员
    onSeek() {
      this.list.page = 1,  //页数重置为1
        this.adminList()
    },
    //请求管理员列表数据w
    adminList() {
      Apiadmin.manager(this.list).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.tableData = res.data.items  //管理员列表数据
          this.total = res.data.count  //分页总数据
        }
      })
      //请求角色枚举
      Apiadmin.intendant().then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.adminrRole = res.data
        }
      })
    },
    // 获取管理员角色名
    getRoleNames(ids) {
      // console.log(ids)
      if (ids instanceof Array) {
        // 过滤出角色名
        return this.adminrRole.filter(item => ids.some(id => id === item.value))
      }
    },
    //添加管理员
    addAdmin() {
      this.title = "添加"
      this.dialogTableVisible = true
      this.showPrise = true  //添加时密码框显示
      this.$nextTick(() => { // 延迟回调,避免未找到重置resetFields的方法
        this.resetForm('ruleForm') // 重置
      })
    },
    //修改管理员
    handleEdit(row) {
      // console.log(row)
      this.title = "修改"
      this.dialogTableVisible = true
      this.ruleForm = row
      this.showPrise = false //修改时密码框隐藏
      // 会修改同一个地址的值，所以需要深度拷贝一下
      this.ruleForm = JSON.parse(JSON.stringify(row));
      this.row = JSON.parse(JSON.stringify(row));
      this.$nextTick(() => {
        this.resetForm('ruleForm') // 重置
      })

    },
    //添加提交按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title == "添加") {
            Apiadmin.addCreate(JSON.stringify(this.ruleForm)).then(res => {
              // console.log(res)
              if (res.errno == 200) {
                this.dialogTableVisible = false  //关闭弹框
                this.adminList()   //刷新页面
                this.initObj(this.ruleForm, {}) //清空数据
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: "管理员已经存在",
                  type: 'error'
                });
              }
            }).catch(err => {
              console.log(err)
            })
          }
          if (this.title == "修改") {
            Apiadmin.addEdit(JSON.stringify(this.ruleForm)).then(res => {
              console.log(res)
              if (res.errno == 200) {
                this.dialogTableVisible = false  //关闭弹框
                this.adminList()   //刷新页面
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: "管理员已经存在",
                  type: 'error'
                });
              }
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
      // 清除或重置
      this.ruleForm = this.title == "添加" ? {} : JSON.parse(JSON.stringify(this.row))
    },
    //删除管理员
    handleDelete(row) {
      Apiadmin.adminDelete(row.id).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.adminList()   //刷新
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.$refs.roll.$el.click?.(".el-main")
      // console.log(`每页 ${val} 条`);
      //在最后一页时，切换没有大小，只发出一次数据请求
      let amount = this.list.limit
      this.list.limit = val
      if (Math.ceil(this.total / amount) == this.list.page) {
        this.list.page = this.pages
      }
      this.adminList()
    },
    handleCurrentChange(val) {
      this.$refs.roll.$el.click?.(".el-main")
      // console.log(`当前页: ${val}`);
      this.list.page = val;
      this.adminList()
    },

  }
}
</script>
<style scoped  lang="less">
.box_input {
  .el-input {
    width: 27%;
  }
}
</style>